package com.one.oa.api.filter;


import com.one.oa.constants.RedisKey;
import com.one.oa.constants.SystemConfig;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Component
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Resource
    private StringRedisTemplate template;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        //1.获取令牌
        String token=request.getHeader(SystemConfig.HEADER_AUTH);
        //2.校验
        if(template.hasKey(RedisKey.AUTH_TOKEN+token)){
            //3.有效 那么就续命
            template.expire(RedisKey.AUTH_TOKEN+token,30, TimeUnit.MINUTES);
            template.expire(RedisKey.AUTH_USER+template.opsForValue().get(RedisKey.AUTH_TOKEN+token),30, TimeUnit.MINUTES);
        }
        filterChain.doFilter(request,servletResponse);
    }
}
